// axios请求封装

import axios from "axios"
// import uuid from 'uuid-v4'
import Cookies from 'js-cookie'
import isTokenExpired from './reftoken.js'

// token刷新标识
let isRefreshing = false
let token = ''

let requests = []

// let base = "/fz-web";
let base = "/sys";
// let syslanguage = Cookie.get('language')

import {
    tokenRef
} from './reqlist.js'

const instance = axios.create({
    baseURL: base,
    timeout: 20000
})

instance.interceptors.request.use(
    config => {
        if (config.url !== '/admin/refreshToken') {
            window.vm.$showLoading()
        }
        if (isTokenExpired() && config.url !== '/admin/login' && config.url !== '/admin/refreshToken') {
            if (!isRefreshing) {
                isRefreshing = true
                let reftoken =Cookies.get('cle')
                tokenRef({ oldToken: reftoken }).then(res => {
                    let update = new Date().getTime();
                    switch (res.data.code) {
                        case 0:
                            isRefreshing = false;
                            token = res.data.data.token;
                            window.vm.$store.commit('setToken', token);
                            window.sessionStorage.setItem('refTime', update);
                            break;
                    
                        default:
                            window.vm.$message.error(res.data.msg);
                            window.vm.$router.push('/login')
                            if (Cookies.get('feed') === 'fake') this.$store.dispatch('logout')
                            Cookies.remove('cle')
                            Cookies.remove('feed')
                            sessionStorage.removeItem('roleMenu')
                            window.sessionStorage.removeItem('userMenuRef')
                            window.sessionStorage.removeItem('activePath')
                    }
                }).then(() => {
                    requests.forEach(cb => cb(token))
                    /* 执行onRefreshed函数后清空数组中保存的请求 */
                    requests = []
                })
            }
            /* 把请求(token)=>{....}都push到一个数组中 */
            let retry = new Promise((resolve) => {
                /* (token) => {...}这个函数就是回调函数 */
                requests.push(() => {
                    config.headers['Authorization'] = token
                    /* 将请求挂起 */
                    resolve(config)
                })
            })
            return retry
        }
        return config;
    }
)

instance.interceptors.response.use(
    response => {
        window.vm.$hideLoading()
        if (response.data) {
            switch (response.data.code) {
                case 401:
                    window.vm.$message.error(response.data.msg)
                    break;
                case 403:
                    window.vm.$message.error(response.data.msg)
                    break;
                case 3:
                    window.vm.$message.error(response.data.msg)
                    break;
                case 1:
                    window.vm.$message.error(response.data.msg)
                    break;
            }
        }
        return response;
    }, err => {
        window.vm.$hideLoading()
        if (err.message.indexOf('timeout') === 0) {
            window.vm.$message.error('请求超时')
        }
        if (err.response) {
            switch (err.response.status) {
                case 500:
                    window.vm.$message.error('服务器错误')
                    break;
            }
        }
        return err;
    }
)

export const postRequest = (url, data, type) => {
    let loginToken = Cookies.get('cle') || ''
    return instance({
        method: "post",
        url,
        data: data,
        headers: {
            "Content-Type": type,
            "Authorization": loginToken
        }
    })
}

export const getRequest = (url, params) => {
    let loginToken = Cookies.get('cle') || ''
    return instance({
        method: "get",
        url,
        params,
        headers: {
            "Authorization": loginToken
        }
    })
}

export const dpwnloadRequest = (url, data, type) => {
    let loginToken = Cookies.get('cle') || ''
    return instance({
        method: "post",
        url,
        data: data,
        headers: {
            "Content-Type": type,
            "Authorization": loginToken
        },
        responseType: 'blob'
    })
}
